package juan.happyge.plugin.myi.view.page;

import juan.happyge.plugin.myi.config.BookConfig;
import juan.happyge.plugin.myi.config.ConfigManage;
import juan.happyge.plugin.myi.service.book.BookService;
import juan.happyge.plugin.myi.utils.VerifyUtils;
import juan.happyge.plugin.myi.view.factory.BookViewFactory;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.regex.Pattern;

public class SettingView {

    BookConfig bookConfig = ConfigManage.getInstance().getBookConfig();

    public JPanel settingJPanel;
    private JPanel bookSettingJPanel;
    private JButton addBookButton;
    private JTextArea tfBookPath;
    private JTextField tfFontSize;
    private JTextField tfPageSize;
    private JTextField tfCrawlerWebsite;


    public SettingView(){
        addBookButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                fileChooser.showOpenDialog(settingJPanel);
                File file = fileChooser.getSelectedFile();
                if(file != null && file.isFile()){
                    tfBookPath.setText(file.getPath());
                }
            }
        });
    }

    public void init(){
        this.initBookConfig();
    }

    private void initBookConfig( ){
        tfBookPath.setText(bookConfig.getBookPath());
        tfFontSize.setText(bookConfig.getFontSize().toString());
        tfPageSize.setText(bookConfig.getPageSize().toString());
        tfCrawlerWebsite.setText("笔趣阁");
    }

    public void save(){
        this.saveBookConfig();
    }

    private BookConfig saveBookConfig(){
        //如果选择书籍改变，重新加载书籍
        String oldBookPath = bookConfig.getBookPath();
        //保存配置
        bookConfig.setBookPath(tfBookPath.getText());
        bookConfig.setCrawlerWebsite(tfCrawlerWebsite.getText());
        if(VerifyUtils.isNumber((tfPageSize.getText()))){
            bookConfig.setPageSize(Integer.parseInt(tfPageSize.getText()));
        }
        if(VerifyUtils.isNumber((tfFontSize.getText()))){
            bookConfig.setFontSize(Integer.parseInt(tfFontSize.getText()));
        }

        if(!oldBookPath.equals(tfBookPath.getText())){
            bookConfig.setLineIndex(0);
            BookViewFactory.bookView.refreshBookViewUI();
        }
        return bookConfig;
    }

}

